const express = require('express')
const authenticate = require('./middleware/authenticate')
const log4js = require('./utils/log4')
const logger = log4js.getLogger('server/app.js')
const expressJWT = require('express-jwt')
const { tokenSecretKey, MultiProcess, MultiProcessNum } = require('./config/index')
const cluster = require('cluster');

const app = express()
const PORT = process.env.EXPRESS_PORT || 3000

// 处理请求json格式
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
// 解析数据
app.use(express.urlencoded({ extended: false }))

// 跨域
const cors = require('cors')
app.use(cors())

// 静态资源
app.use(express.static('./uploads'))


app.use(function (req, res, next) {
  logger.debug(`original-URL:${req.headers['x-original-uri']}`)
  logger.debug(`URL:${req.originalUrl}`)
  next()
})

// 封装res.send()方法
app.use((req, res, next) => {
  res.cc = function (err, status = 0) {
    logger.error(err instanceof Error ? err.message : err)
    res.send({
      status,
      message: err instanceof Error ? err.message : err,
      data: null
    })
  }
  next()
})

// 引入路由
// 登录
const loginRouter = require('./router/auth')
app.use('/api', loginRouter)

// 使用鉴权中间件
// app.use(authenticate)
app.use(expressJWT({ secret: tokenSecretKey }).unless({
  path: [
    /^\/uploads\//
  ]
}))

// 后台管理员
const adminRouter = require('./router/admin')
app.use('/api', adminRouter)
// catch 404 and forward to error handler
app.use(function (req, res, next) {
  logger.error(`URL:${req.url} 404`)
  next()
})


// error handler
app.use(function (err, req, res, next) {
  logger.error(err)
  if (err.name === 'UnauthorizedError') {
    res.status(401)
    return res.send({ status: 401, message: 'Invalid token' })
  }
  res.status(err.status || 500).json({ code: err.status || 500, message: err.message })
})


if (!MultiProcess) {
  //单进程模式
  app.listen(PORT, function () {
    logger.info(`单进程模式启动`)
    logger.info(`server is running at http://127.0.0.1:${PORT}`)
    logger.info('单进程PID:' + process.pid)
  });
} else {
  //多进程模式
  if (cluster.isMaster) {
    logger.info(`多进程模式启动`)
    logger.info(`主进程 ${process.pid} 正在运行，进程及cpus：0,runing at http://127.0.0.1:3007`);
    for (let i = 0; i < MultiProcessNum; i++) { // 衍生工作进程，两核心三进程。
      cluster.fork();
    }
  } else {
    app.listen(PORT, function () {
      logger.info('子进程PID:' + process.pid)
    });
  }
  // 主进程接收子进程的消息
  cluster.on('message', data => {
    logger.info('主进程接收到的信息：', data);
  })
}
// app.listen(PORT, () => {
//   console.log(process.env.MYSQL_HOST,Number(process.env.MYSQL_PORT),process.env.MYSQL_USER,process.env.MYSQL_PASSWORD,process.env.MYSQL_DATABASE)
//   logger.info(`server is running at http://127.0.0.1:${PORT}`)
// })
